# -*- coding: utf-8 -*-
import traceback
import sys
import os
import json

from data_printer import show_data

# 各端 单测覆盖率 执行脚本
# key: 平台名称，对应当前脚本所在目录的文件夹名称
# value: 单侧脚本的相对路径
# eg: D:\workspace01\Android-APT\UnitTestCoverageDemo\unit_test_coverage\Android\scripts\main.py
platform_script = {
    "Android" : r"Android\scripts\main.py",
    "iOS" : "",
    "Flutter" : "",
    "Unity" : "",
}

# 删除文件夹
def remove_folder(path):
    if os.path.exists(path):
        if os.path.isfile(path) or os.path.islink(path):
            os.remove(path)
        else:
            for filename in os.listdir(path):
                remove_folder(os.path.join(path, filename))
            os.rmdir(path)


def main() :
    global platform_script

    if len(sys.argv) < 2:
        # 拼接平台名称，控制台输出提示
        platform_str = ""
        for key in platform_script:
            platform_str += f"{key} "
        print(f"please input one of the platform: {platform_str}")
        return 1
    platform = sys.argv[1]

    
    # 找出各端的脚本文件路径，platform输入填错了就会找不到
    platform_script_path = ""
    for key in platform_script:
        if key == platform:
            platform_script_path = platform_script[key]
            break
    if platform_script_path == "":
        print(f"the input platform: {platform} is not support, please check it out")
        return 1


    print("-----------------------------------------------------------------------------")
    print(f"----------------- building [{platform}] unit test coverage -----------------")

    

    script_path = os.path.abspath(__file__) # 脚本所在绝对路径
    dir_path = os.path.dirname(script_path) # 脚本目录绝对路径
    build_dir = os.path.join(dir_path,"build") # 构建文件绝对路径，存放json
    platform_script_path = os.path.join(dir_path, platform_script_path) # 各端运行脚本的绝对路径
    json_path = os.path.join(build_dir,"result.json") # 单测覆盖率结果json文件，绝对路径
    # print(f"build_path: {build_path}")

    # 删除build缓存，重新创建build文件夹
    remove_folder(build_dir)
    os.makedirs(build_dir, exist_ok=True)
    # 先把单测覆盖率json文件创建好了，再传递给各端脚本
    open(json_path,"w").close()
    
    # 执行各端脚本，单测覆盖率结果需写入到json_path文件中
    print("execute command:")
    cmd = r"python3 {} {}".format(platform_script_path, json_path)
    print(cmd)
    os.system(cmd)

    # 读取json_path中的内容，屏显+判断是否通过
    print(f"json path: {json_path}")
    with open(json_path,"r") as json_file:
        json_obj = json.load(json_file)

    # 把数据打印到面板上
    show_data(json_obj)

    

    
    print(f"----------------- finished [{platform}] unit test coverage -----------------")
    print("-----------------------------------------------------------------------------")
    return 0


# main函数入口
if __name__ == '__main__':
    sys_ret = 0
    try:
        sys_ret = main()
    except Exception as e:
        print(e)
        traceback.print_exc()
        sys_ret = 1
    finally:
        sys.exit(sys_ret)

